import axios from "axios";
import { Loading, Message } from "element-ui";
import store from "../store";

axios.defaults.timeout = 5000;
//var loadinginstace;

axios.interceptors.request.use(
  (config) => {
    if (store.state.auth) {
      // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers.Authorization = `Bearer ${store.state.auth.access_token}`;
    }
    // loadinginstace = Loading.service({ fullscreen: false });
    return config;
  },
  (err) => {
    //loadinginstace.close();
    return Promise.reject(err);
  }
);
axios.interceptors.response.use(
  function(response) {
    // do something for the response data
    //loadinginstace.close();
    return response;
  },
  function(err) {
    //loadinginstace.close();
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          if (err.response.data) {
            if (err.response.data.errors) {
              //后台ViewModel验证出错
              err.message = "";
              Object.keys(err.response.data.errors).forEach(function(index) {
                err.message += err.response.data.errors[index];
              });
            } else {
              //其他错误
              err.message = err.response.data;
            }
          } else {
            //一般错误
            err.message = "请求错误(400)";
          }
          break;
        case 401:
          err.message = "未授权，请重新登录(401)";
          store.commit("setLogout");
          break;
        case 403:
          err.message = "拒绝访问(403)";
          store.commit("setAccessDeny");
          break;
        case 404:
          err.message = "资源未找到(404)";
          break;
        case 408:
          err.message = "请求超时(408)";
          break;
        case 500:
          if (err.response.data.title) {
            err.message = "服务器错误(500):" + err.response.data.title;
          } else {
            err.message = "服务器错误(500)";
          }

          break;
        case 501:
          err.message = "服务未实现(501)";
          break;
        case 502:
          err.message = "网络错误(502)";
          break;
        case 503:
          err.message = "服务不可用(503)";
          break;
        case 504:
          err.message = "网络超时(504)";
          break;
        case 505:
          err.message = "HTTP版本不受支持(505)";
          break;
        default:
          err.message = `连接出错(${err.response.status})!`;
      }
    } else {
      err.message = "连接服务器失败!";
    }
    Message.error({
      message: err.message,
    });

    return Promise.reject(err);
  }
);

export default axios;
